import 'dart:convert';
import 'dart:io';

import 'package:emby/pages/login/login.dart';
import 'package:emby/model/user.dart';
import 'package:emby/util/function.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:emby/server/add.dart';
import 'package:oktoast/oktoast.dart';
import 'pages/home.dart';
import 'model/server.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //获取保存的服务器
  List<Server> servers = [];
  String serverStr = await Util.getStorage("services");
  print(serverStr);
  if (serverStr != null && serverStr != "") {
    servers = json.decode(serverStr).map<Server>((server) {
      return Server.fromJson(server);
    }).toList();
  } else {
    servers = [];
  }
  String accessToken = await Util.getStorage("access_token");
  await Util.setToken(accessToken);
  String userId = await Util.getStorage("user_id");
  await Util.setUserId(userId);
  String host = await Util.getStorage("host");
  Util.setBaseUrl(host);
  runApp(EmbyApp(servers, accessToken));
  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class EmbyApp extends StatelessWidget {
  List servers;
  String accessToken;
  EmbyApp(this.servers, this.accessToken);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return OKToast(
      child: MaterialApp(
        title: 'Emby Player',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: servers.length == 0 ? AddServer() : accessToken != null && accessToken != "" ? HomePage() : Login(),
        routes: {
          "/homePage": (BuildContext context) => HomePage(),
          "/loginPage": (BuildContext context) => Login(),
        },
      ),
    );
  }
}
